package com.doge.calcalbum.business.calc

import android.app.Dialog
import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.WindowManager
import com.doge.calcalbum.R
import com.doge.calcalbum.databinding.DialogRemindPwdBinding
import com.doge.calcalbum.utils.*

class RemindPwdDialog private constructor(context: Context, theme: Int) : Dialog(context, theme) {
    private class Params {
        lateinit var mContext: Context
        lateinit var binding: DialogRemindPwdBinding
        var canCancel = false
    }

    class Builder(context: Context) {
        private val p = Params()

        init {
            p.mContext = context
        }

        fun create(): RemindPwdDialog {
            val dialog = RemindPwdDialog(
                p.mContext,
                R.style.Theme_Light_NoTitle_Dialog
            )

            dialog.window?.decorView?.setPadding(37.dp, 0, 37.dp, 0)
            val lp = dialog.window?.attributes
            lp?.width = WindowManager.LayoutParams.MATCH_PARENT
            lp?.height = WindowManager.LayoutParams.WRAP_CONTENT
            dialog.window?.attributes = lp

            p.binding = DialogRemindPwdBinding.inflate(LayoutInflater.from(p.mContext))

            val flag = getString(R.string.remind_pwd_desc_bold_flag1)
            val desc = getString(R.string.remind_pwd_desc)
            val descValue = SpannableString(desc)
            val index = desc.indexOf(flag)
            descValue.setSpan(StyleSpan(Typeface.BOLD), index, index + flag.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            p.binding.message.text = descValue

            p.binding.confirm.isEnabled = true
            p.binding.confirm.setOnClickCallback {
                dialog.dismiss()
            }
            val countdown = 0
            p.binding.confirm.text =
                if (countdown <= 0) getString(R.string.ok) else "${getString(R.string.ok)}($countdown)"
            p.binding.confirm.isEnabled = countdown <= 0
            p.binding.confirm.setBackgroundResource(
                if (countdown <= 0)
                    R.drawable.ripple_alert_confirm_btn else R.drawable.ripple_alert_cancel_btn
            )
            p.binding.confirm.setTextColor(
                getColor(if (countdown <= 0) "#FFFFFF" else "#999999")
            )

            dialog.setContentView(p.binding.root)
            dialog.setCanceledOnTouchOutside(p.canCancel)
            dialog.setCancelable(p.canCancel)
            return dialog
        }
    }
}